/**
 * 去重
 * 输入：Array, 'id'
 * 输出：[{id: '01', name: 'name01'}, {id: '02', name: 'name02'}, {id: '03', name: 'name03'}]
 */
export function uniqueArrayOfObjectsByKeys(arr, key) {
    return arr.filter((item, index, self) => {
        return self.findIndex(t => t[key] === item[key]) === index
    })
}
/**
 * 邮箱校验
 */
export function checkEmail(email) {
    const patt = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/

    return patt.test(email)
}
/**
 * 电话号码校验
 */
export function checkPhone(phone) {
    const isMobilePhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/
    const isFixMob = /^\s*\+?\s*(\(\s*\d+\s*\)|\d+)(\s*-?\s*(\(\s*\d+\s*\)|\s*\d+\s*))*\s*$/

    return isMobilePhone.test(phone) || isFixMob.test(phone)
}
/**
 * 身份证号码校验
 */
export function checkIdentityCard(cardid) {
    const patt = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

    return patt.test(cardid)
}
/**
 * 邮编校验
 */
export function checkPostCode(postCode) {
    const patt = /^[\d]{6}$/

    return patt.test(postCode)
}
/**
 * web地址校验
 */
export function checkWebAddress(url) {
    const patt = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/

    return patt.test(url)
}
/**
 * 获取当前页面url参数
 * 输入：'name'
 * 输出：'张三'
 */
export function getUrlParam(code) {
    let url = window.location.href
    let p = url.split("?")[1]
    let params = new URLSearchParams(p)

    return params.get(code)
}
/**
 * 隐藏字符串的第几位到倒数第几位，用*代替
 * 输入：'1234567890', 3, 5
 * 输出：'123**67890'
 */
export function hideStringFromTo(str, from, to) {
    let Str = str + ''
    return (
        Str.substring(0, from) +
        Str.substring(from, Str.length - to).replace(/./g, '*') +
        Str.substring(Str.length - to, Str.length)
    )
}
/**
 * 隐藏字符串，用*代替
 * 输入：'1234567890', true,
 * 输出：'****'
 */
export function hideString(str, boo) {
    if (boo) {
        return '****'
    } else {
        return str
    }
}
/**
 * 判断该元素，是否有该class类
 */
export function hasClass(el, className) {
    const reg = new RegExp('(^|\\s)' + className + '(\\s|$)')

    return reg.test(el.className)
}
/**
* 给该元素添加该class类
*/
export function addClass(el, className) {
    if (hasClass(el, className)) {
        return
    }

    const newClass = el.className.split(' ')
    newClass.push(className)
    el.className = newClass.join(' ')
}
/**
* 给该元素删除该class类
*/
export function removeClass(el, className) {
    if (!hasClass(el, className)) {
        return
    }

    const reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
    el.className = el.className.replace(reg, ' ')
}
